<template>
  <div class="app-container" ref="appcontainer">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目经理" prop="projectManagerId" v-if="is_yezhu==0">
        <el-select v-model="queryParams.projectManagerName" placeholder="请选择项目经理" size="small">
          <el-option v-for="dict in personList" :key="dict.nickName" :label="dict.nickName" :value="dict.nickName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工程名称" prop="engineeringName">
        <el-input v-model="queryParams.engineeringName" placeholder="请输入工程名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="框架名称" prop="engineeringName">
        <el-input v-model="queryParams.subItem" placeholder="请输入框架名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="业主单位" >
        <el-input v-model="queryParams.enterpriseName" placeholder="请输入业主单位" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="日期筛选">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        
        
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          style="margin-left: 40px"
        >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-show="roleId != 6">
        <el-button type="primary" plain icon="" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-show="roleId != 6">
        <el-button type="primary" plain icon="" size="mini" @click="handleImport">导入
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-if="false">导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :height="tableHeight" :data="enterpriseList"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column v-if="is_yezhu == 0" label="工程编号" align="center" prop="engineeringNumber" />
      <el-table-column label="工程名称" align="center" prop="engineeringName" width="120" />
      <el-table-column label="框架名称" align="center" prop="subItem" width="120" />
      <el-table-column v-if="is_yezhu == 0" label="项目经理" align="center" prop="projectManagerName" />
      <el-table-column v-if="is_yezhu == 0" label="试验员" align="center" prop="testPeopleName" />
      <el-table-column label="业主单位" align="center" prop="enterpriseName" />
      <el-table-column label="检测项目" align="center" prop="testProject" width="120">
<!--        <template slot-scope="scope">-->
<!--          <div v-if="scope.row.businessType == 'shinei'">-->
<!--            <div v-for="item in scope.row.sampleList" :key="item.id">{{ detectionOptions[item.project] }} <a-->
<!--                style="color:blue;text-decoration: underline;">{{ item.number }}</a></div>-->
<!--          </div>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="工作总量" align="center" prop="total" />
      <el-table-column label="完成数量" align="center" prop="doneNum" />
      <el-table-column label="累计完成数量" align="center" prop="doneTotalNum" />
        
      <el-table-column label="完成工作量（%）" align="center" prop="doneTotal" >
      <template slot-scope="scope">
          {{scope.row.doneTotal}}%
        </template>
      </el-table-column>
      <!-- <el-table-column label="月份" align="center" prop="yuefen" /> -->
      <el-table-column label="创建时间" align="center" prop="createTime" width="150" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="roleId != 6">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改任务对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="工程名称" prop="engineeringId">
          <el-select v-model="form.engineeringId" placeholder="请选择工程"  @change="selectEngineeringInfo()">
            <el-option v-for="item in engineeringOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item  label="项目经理" prop="projectManagerName">
          <el-input ref="projectManagerName" v-model="form.projectManagerName" disabled="true" placeholder="请输入项目经理"  clearable size="small"
            />
        </el-form-item>
        

        <el-form-item label="检测项目" prop="testProject">
          <el-select v-model="form.testProject" placeholder="请选择检测项目" >
            <el-option v-for="dict in detectionOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictLabel"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工程总量" prop="total">
          <el-input v-model="form.total" placeholder="请输入工程总量" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="完成数量" prop="doneNum">
          <el-input v-model="form.doneNum" placeholder="请输入完成数量" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="总计完成数量" prop="doneTotalNum">
          <el-input v-model="form.doneTotalNum" placeholder="请输入总计完成数量" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="完成工作量" prop="doneTotal">
          <el-input v-model="form.doneTotal" placeholder="请输入完成工作量" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>

        <el-form-item
          label="备注"
          prop="ipaddr"
          style="margin-bottom: 10px"
        >
          <el-input
            type="textarea"
            v-model="form.remark"
            :rows="4"
          ></el-input>
        </el-form-item>
         
        <!-- <el-form-item label="月份" prop="yuefen">
          <el-input
            v-model="form.yuefen"
            placeholder="请输入月份"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 周报导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importWeeklyReportTemplate">下载模板</el-link> -->
          <a :href="file1Url" download="项目执行情况汇总表模板.xlsx" style="list-style: none;color: #1176FF;">模版下载</a>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import file1Url from '@/assets/download/项目执行情况汇总表模板.xlsx';
import {
  listInfo,
  addInfo,
  updateInfo,
  delInfo,
  getInfo, importWeeklyReportTemplate,
} from "@/api/task/bulletin/bulletin";

import {listEnterpriseAll, ProjectSingleList, searchProject} from "@/api/enterprise/enterprise";
import { getComment, addComment } from "@/api/task/info/info";
import { listPerson } from "@/api/staff";
import Cookies from "js-cookie";
import {getToken} from "@/utils/auth";
import {listAllUser} from "@/api/system/user";
import {exportWeeklyReport,getProjectManagerName} from "@/api/weeklyReport/weeklyReport";

export default {
  name: "Enterprise",
  data() {
    return {
      file1Url,
      detectionOptions: [],
      // 所有工程
      list: [],
      // 检测类别
      weekOptions: [],
      // 附言历史
      commentList: [],
      engineeringSearch:{},
      // 人员列表
      personList: [],
      tableHeight: 0,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息表格数据
      enterpriseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 企业类型字典
      typeOptions: [],
      // 状态 1=开业，2=停业字典
      statusOptions: [],
      engineeringOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        engineeringName: "",
        projectManagerId: "",
        engineeringType: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        code: [
          { required: true, message: "社会信用代码不能为空", trigger: "blur" },
        ],
        entrustCode: [
          { required: true, message: "委托单编号不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        content: [
          { required: true, message: "任务内容不能为空", trigger: "blur" },
        ],
      },
      roleId: null,
      roles:[],
      enterpriseId: null,
      // 周报导入参数
      upload: {
        // 是否显示弹出层（周报导入）
        open: false,
        // 弹出层标题（周报导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的周报数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/weeklyReport/weeklyReport/importData"
      },
      is_yezhu:0,
      // 日期范围
      dateRange: [],
    };
  },
  created() {
    this.getProject()
    //当前用户的信息
    let userInfo = JSON.parse(Cookies.get("userinfo"));
    this.roles = userInfo.roles
    this.roleId = userInfo.roleId
    this.enterpriseId = userInfo.enterpriseId

    //业主不让看 工程编号 和 项目经理
    for(let i=0; i < this.roles.length;i++){
      if(this.roles[i].roleId == 6 || this.roles[i].roleId == 9){
        this.is_yezhu = 1
      }
    }

    this.getList();
    this.calHeight();
    this.getDicts("gc_weekly_report_test_type").then((response) => {
      this.weekOptions = response.data;
    });
    this.getDicts("gc_engineering_stage").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("gc_engineering_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getProjectType1();
    this.getProjectType();

   this.getPerson();
  },
  watch: {
    showSearch: "calHeight",
  },
  methods: {
    // getEnterpriseAll() {
    //   listEnterpriseAll().then((res) => {
    //     this.list = res.data;
    //   });
    // },
    
    // selectEngineeringInfo(){
    //   console.log(this.form)
    //   getProjectManagerName(this.form.engineeringId).then(res => {
    //     this.form.projectManagerName = res.msg
    //   })
    // },

    async selectEngineeringInfo() {
      this.isLoading = true; // 显示加载状态
      try {
        const response = await getProjectManagerName(this.form.engineeringId); // 假设这是你的API请求函数
        console.log(response)
        this.form.projectManagerName = response.msg; // 更新数据源或相关数据
        this.$refs.projectManagerName.value = response.msg; 
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        this.isLoading = false; // 请求完成后关闭加载状态
      }
    },

    
    getProjectType(){
          this.getDicts("detection_item_indoor").then(response => {
            this.detectionOptions.push(...response.data);
          });
    },
    getProjectType1(){
      this.getDicts("detection_item_scene").then(response => {
          this.detectionOptions.push(...response.data);
      });
    },
    // 获取人员信息
    getPerson() {
      listAllUser({ roleId: 4 }).then(response => {
          this.personList = response .data
        console.log("11adsa11",this.personList)
          });
    },
     //工程信息查询所有
    getProject() {
      //console.log(this.roles)
      for (let i = 0; i < this.roles.length; i++) {
        //console.log()
        if (this.roles[i].roleId == 6) {
          this.engineeringSearch.enterpriseId = this.enterpriseId
          break;
        }
      }
      searchProject(this.engineeringSearch).then((res) => {
        this.engineeringOptions = res.data;
      });
    },
    calHeight() {
      this.$nextTick(() => {
        const rect = this.$refs.appcontainer.getBoundingClientRect();
        let height = this.$refs.queryForm.$el.offsetHeight;
        this.tableHeight = rect.height - height - 120;
      });
    },
    /** 查询企业信息列表 */
    getList() {
      this.loading = true;
      
      this.queryParams.isRoleShow = 1
      listInfo(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.enterpriseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        code: null,
        type: null,
        contacts: null,
        mobile: null,
        status: 0,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.showSearch = true;
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "周报导入";
      this.upload.open = true;
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    /** 下载模板操作 */
    importWeeklyReportTemplate() {
      importWeeklyReportTemplate().then(response => {
        this.download(response.msg);
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        engineeringName: "",
        projectManagerId: "",
        engineeringType: ""
      }
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加进度";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // // 查询附言历史
      // getComment({ taskId: row.id }).then((res) => {
      //   this.commentList = res;
      // });
      const id = row.id || this.ids;
      getInfo(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改进度";
        ProjectSingleList(response.data.engineeringId).then(res => {
          this.form.engineeringId = res.data.id
          this.form.projectManagerId = res.data.projectManagerId
          this.form.stage = res.data.stage
          this.form.type = res.data.type
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        console.log("w32313212",this.form)
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInfo(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delInfo(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const ids = this.ids;
      this.queryParams.ids = ids
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出进度管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportWeeklyReport(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => { });
    },
  },
};
</script>

<style scoped>
.list {
  padding: 0;
  margin: 0 20px;
}
</style>
